package com.atguigu.yygh.hosp.listener;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.rabbit.constaner.MqConst;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author luoyin
 * @Date 18:18 2022/10/10
 **/
@Component
public class RabbitMqListener {

    @Autowired
    private ScheduleService scheduleService;

    @RabbitListener(
            bindings = @QueueBinding(exchange = @Exchange(MqConst.EXCHANGE_DIRECT_ORDER),
            value = @Queue(MqConst.QUEUE_ORDER),key = MqConst.ROUTING_ORDER)
    )
    public void getMessage(Message message , Channel channel , OrderMqVo orderMqVo){
        Schedule schedule = new Schedule();
        if (orderMqVo.getAvailableNumber() != null){
            //更改库存
            schedule.setId(orderMqVo.getScheduleId());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
        }else {
            String[] splits = orderMqVo.getScheduleId().split(":");
            schedule = scheduleService.selectSchedule(splits[0],splits[1],splits[2]);
            schedule.setAvailableNumber(schedule.getAvailableNumber() + 1);
        }
        scheduleService.update(schedule);
    }
}
